package com.atguigu.gmall.payment.interceptors;

import com.atguigu.gmall.common.bean.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    //public Long userId;
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 获取请求头信息中的userId，传递给后续操作
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(Long.valueOf(userId));
            // 通过thread_local传递给后续业务逻辑
            THREAD_LOCAL.set(userInfo);
        }

        return true;
    }

    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 由于使用的是tomcat线程池，所以请求结束，线程没有结束。否则就会引发内存泄漏
        THREAD_LOCAL.remove();
    }
}
